package com.weijian.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weijian.entity.VideoPlaybackProgress;
import com.weijian.mapper.VideoPlaybackProgressMapper;
import com.weijian.service.VideoPlaybackProgressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 视频播放进度Service实现类
 */
@Slf4j
@Service
public class VideoPlaybackProgressServiceImpl extends ServiceImpl<VideoPlaybackProgressMapper, VideoPlaybackProgress>
        implements VideoPlaybackProgressService {

    @Override
    public boolean saveOrUpdateProgress(Long userId, Long videoId, Integer progress, Integer duration) {
        try {
            // 查询是否已存在播放记录
            VideoPlaybackProgress playbackProgress = baseMapper.selectByUserIdAndVideoId(userId, videoId);

            if (playbackProgress == null) {
                // 创建新的播放记录
                playbackProgress = new VideoPlaybackProgress();
                playbackProgress.setUserId(userId);
                playbackProgress.setVideoId(videoId);
                playbackProgress.setProgress(progress);
                playbackProgress.setDuration(duration);
                playbackProgress.setCreateTime(LocalDateTime.now());
                playbackProgress.setUpdateTime(LocalDateTime.now());
                baseMapper.insert(playbackProgress);
            } else {
                // 更新播放进度
                playbackProgress.setProgress(progress);
                playbackProgress.setDuration(duration);
                playbackProgress.setUpdateTime(LocalDateTime.now());
                baseMapper.updateById(playbackProgress);
            }

            return true;
        } catch (Exception e) {
            log.error("保存播放进度失败: userId={}, videoId={}, progress={}", userId, videoId, progress, e);
            return false;
        }
    }

    @Override
    public VideoPlaybackProgress getProgressByUserAndVideo(Long userId, Long videoId) {
        return baseMapper.selectByUserIdAndVideoId(userId, videoId);
    }
}
